<template>
	<view class="add-work-main">
		<view class="work-info">
			<view class="equipment_text">
				工单信息
			</view>
			<view class="work-info-body global_box">
				<view class="display-item">
					<view class="left require">
						联系人
					</view>
					<view class="right">
						<input type="text" v-model="form.contactUser" placeholder="请输入"
							placeholder-style="text-align:right;">
					</view>
				</view>
				<view class="display-item">
					<view class="left require">
						联系电话
					</view>
					<view class="right">
						<input type="text" v-model="form.contactPhone" placeholder="请输入"
							placeholder-style="text-align:right;">
					</view>
				</view>
				<view @click="checkBusinessHandle" class="display-item">
					<view class="left require">
						选择业务
					</view>
					<view class="right">
						{{ form.flagName ? form.flagName : '请选择' }}
						<image
							src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/Vector_stroke.png">
						</image>
					</view>
				</view>
				<picker mode="multiSelector" @change="startTimeChangeHandle" :range="dateTimeArray" :value="dateTime">
					<view class="display-item">
						<view class="left require">
							工单开始时间
						</view>
						<view class="right">
							{{ form.startDate ? form.startDate : '请选择' }}
							<image
								src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/Vector_stroke.png">
							</image>
						</view>
					</view>
				</picker>
				<picker mode="multiSelector" @change="endTimeChangeHandle" :range="dateTimeArray" :value="dateTime">
					<view class="display-item">
						<view class="left">
							工单结束时间
						</view>
						<view class="right">
							{{ form.endDate ? form.endDate : '请选择' }}
							<image
								src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/Vector_stroke.png">
							</image>
						</view>
					</view>
				</picker>
				<view class="display-item" @click="selectStaffHandle2">
					<view class="left">
						指派执行人
					</view>
					<view class="right">
						{{ form.executorName ? form.executorName : '请选择' }}
						<image
							src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/Vector_stroke.png">
						</image>
					</view>
				</view>
				<view class="display-item" @click="selectStaffHandle1">
					<view class="left">
						指派验收人
					</view>
					<view class="right">
						{{ form.accepterName ? form.accepterName : '请选择' }}
						<image
							src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/Vector_stroke.png">
						</image>
					</view>
				</view>
				<view class="display-content">
					<view class="label">
						工单内容
					</view>
					<view class="label-body">
						<textarea style="height:120rpx" v-model="form.orderContent" placeholder="请输入内容"></textarea>
					</view>
				</view>
			</view>
		</view>
		<view class="img-list">
			<view v-for="(item, index) in tempFilePaths" :key="index">
				<image class="uploadImg mr20" :src="item" mode="aspectFit|aspectFill|widthFix" lazy-load="false">
				</image>
			</view>
			<image v-if="!form.imgPaths||form.imgPaths.length<3" class="uploadImg mr20 mt15"
				src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/bus/camera01.png"
				mode="aspectFit|aspectFill|widthFix" lazy-load="false" @click="tapchoosePhoto"></image>
		</view>
		<view class="job-object">
			<view class="equipment_text">
				作业对象
			</view>
			<view class="global_box">
				<view class="display-item" @click="chekcObjTypeHandle">
					<view class="left">
						对象类型
					</view>
					<view class="right">
						<text
							v-if="JSON.stringify(checkItemData)=='{}'">{{ objTypeIndex == undefined ? '请选择' : objList[objTypeIndex] }}</text>
						<text v-else>{{ checkItemData.objectType==0 ? '设备' : '空间' }}</text>
					</view>
				</view>
			</view>
			<view class="job-object-list">
				<view class="item global_box" @click="checkJobClassPage(item,index)" v-for="(item,index) in workOrderObjects" :key="item.id">
					<view class="text1">
						<view class="left">
							[<text>{{ item.objectType==0 ? '设备' : '空间' }}</text>]
							<text>{{item.name}}</text>
						</view>
						<text class="right">
							<text v-if="item.procedureId" class="on">{{item.procedureName}}作业标准</text>
							<text v-else class="off">未配置作业标准</text>
						</text>
					</view>
					<view class="text2">
						<image v-if="item.joint || item.address"
							src="https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/icons/location.png">
						</image>
						<text>{{ item.joint || item.address || "" }}</text>
					</view>
				</view>
			</view>
			<view class="add-job-class" @click="addJobObjHandle">
				➕新增作业对象
			</view>
		</view>
		<view class="footer" @click="addWorkHandle">
			提交
		</view>
	</view>
</template>

<script>
	import dateTimePicker from "../utils/dateTimePicker.js"
	import {
		baseUrl,
		request
	} from "../../request/index.js"

	export default {
		data() {
			return {
				bj_img: 'https://fireware-1257276602.cos.ap-guangzhou.myqcloud.com/fsw-wx-lmini/icons/uploadImg.png',
				objTypeIndex: undefined, // 1-空间 0-设备
				objList: ['设备', '空间'],
				workOrderObjects: [],
				startYear: 2020,
				endYear: 2050,
				dateTimeArray: [],
				tempFilePaths: [],
				currentTime: "",
				dateTime: "",
				checkItemData: {},
				form: {
					projectId: uni.getStorageSync("projectId") || "16154516457903604960000255341083",
					name: "",
					startDate: "",
					endDate: "",
					baseFlagName: "", //  业务分类标识
					contactPhone: "", //  联系人电话
					contactUser: "",
					orderContent: "", // 工单内容
					executorId: "", //  执行人id
					accepterId: "", //  验收人id
					imgPaths: [],
					workOrderObjects: [
						// {
						// 	procedureId:"",
						// 	objectId:"",
						// 	objectType:"",
						// 	orderFlag:"",
						// }
					],

				}
			};
		},
		onLoad(options) {
			//  时间初始化
			const mydate = new Date();
			this.currentTime = mydate.toLocaleDateString() + ' ' + mydate.getHours() + ':' + mydate.getMinutes() + ':' +
				mydate.getSeconds()
			var obj = dateTimePicker.dateTimePicker(this.startYear, this.endYear, this.currentTime);
			this.dateTimeArray = obj.dateTimeArray
			this.dateTime = obj.dateTime

			//  校验是否有验收人
			this.hasAccepterHandle()

			if (options.checkItemData) {
				this.checkItemData = JSON.parse(options.checkItemData)
				this.objTypeIndex = this.checkItemData.objectType
				const tempObj = {
					objectType: this.checkItemData.objectType,
					objectId: this.checkItemData.id,
					orderFlag: 0,
					name: this.checkItemData.objectInfo.name
				}
				if (this.checkItemData.objectType == 0) tempObj.address = this.checkItemData.spaceAddress
				else if (this.checkItemData.objectType == 2) tempObj.joint = this.checkItemData.spaceAddress
				this.workOrderObjects.push(tempObj)
			}
		},
		methods: {
			chekcObjTypeHandle() {
				uni.showActionSheet({
					itemList: this.objList,
					itemColor: '#000000',
					success: (result) => {
						this.objTypeIndex = result.tapIndex
						this.workOrderObjects = []
					},
					fail: () => {},
					complete: () => {}
				});
			},
			async hasAccepterHandle() {
				const res = await request({
					url: "api/oct/wemini/bus/workOrder/hasAcceptStep",
					method: "POST",
					data: {}
				})
				if (res.status == 0) {

				} else {
					uni.showToast({
						title: "验收人权限校验失败!",
						duration: 2000
					})
				}
			},
			startTimeChangeHandle(e) {
				//  获取开始时间
				const timeIndexList = e.detail.value
				const source = this.dateTimeArray
				const time = source[0][timeIndexList[0]] + '-' + source[2][timeIndexList[2]] + '-' + source[4][
					timeIndexList[4]
				] + ' ' + source[6][timeIndexList[6]] + ':' + source[8][timeIndexList[8]] + ':' + source[10][
					timeIndexList[10]
				]

				if (this.form.endDate) {
					//  对比开始与结束时间的时间戳
					const start = new Date(time).getTime()
					const end = new Date(this.form.endDate).getTime()
					if (start < end) {
						this.form.endDate = time
					} else {
						uni.showToast({
							title: '开始时间必须小于结束时间!',
							icon: 'none',
							duration: 2000,
						})
					}
				} else this.form.startDate = time
			},
			endTimeChangeHandle(e) {
				//  获取结束时间
				const timeIndexList = e.detail.value
				const source = this.dateTimeArray
				const time = source[0][timeIndexList[0]] + '-' + source[2][timeIndexList[2]] + '-' + source[4][
					timeIndexList[4]
				] + ' ' + source[6][timeIndexList[6]] + ':' + source[8][timeIndexList[8]] + ':' + source[10][
					timeIndexList[10]
				]

				if (this.form.startDate) {
					//  对比开始与结束时间的时间戳
					const start = new Date(this.form.startDate).getTime()
					const end = new Date(time).getTime()
					if (start < end) {
						this.form.endDate = time
					} else {
						uni.showToast({
							title: '结束时间不能小于开始时间!',
							icon: 'none',
							duration: 2000,
						})
					}
				} else this.form.endDate = time
			},
			async addWorkHandle() {
				//  校验必填项
				if (!this.form.contactUser || !this.form.contactPhone || !this.form.baseFlagName || !this.form
					.startDate) return uni.showToast({
					title: "有必填项尚未填写",
					icon: "none",
					duration: 2000
				})

				// 过滤参数
				this.form.workOrderObjects = this.workOrderObjects.map(item => {
					return {
						procedureId: item.procedureId,
						objectType: item.objectType,
						objectId: item.id,
						orderFlag: 0
					}
				})
				const res = await request({
					url: "api/oct/wemini/bus/workOrder/addTmpWorkOrder",
					method: "POST",
					data: this.form
				})
				if (res.status == 0) {
					if (res.payload.id) {
						uni.showToast({
							title: "新增工单成功!",
							icon: "none",
							duration: 2000
						})
						return uni.navigateBack({
							delta: 1
						})
					}
					uni.showToast({
						title: "新增工单成功!",
						icon: "none",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: `新增工单失败!${res.description}`,
						icon: "none",
						duration: 2000
					})
				}
			},
			selectStaffHandle1() {
				//  跳转验收人
				uni.navigateTo({
					url: "../select-staff/select-staff?type=acceptor&title=指派验收人"
				})
			},
			selectStaffHandle2() {
				//  跳转执行人
				uni.navigateTo({
					url: "../select-staff/select-staff?type=executor&title=指派执行人"
				})
			},
			checkBusinessHandle() {
				uni.navigateTo({
					url: '../select-space/select-space?type=business'
				})
			},
			checkJobClassPage(item, index) {
				console.log('item', item);
				console.log('index', index);
				//  拿到选中作业的index
				uni.navigateTo({
					url: `../select-job-standard/select-job-standard?procedureId=${(item && item.procedureId) || {}}&index=${index}`
				})

			},
			addJobObjHandle() {
				if (this.objTypeIndex == undefined) return uni.showToast({
					title: "请选择对象类型",
					icon: 'none',
					duration: 2000
				})
				if (this.objTypeIndex == 1 || this.objTypeIndex == 2) {
					uni.navigateTo({
						url: "../select-space/select-space?type=space"
					})
				} else if (this.objTypeIndex == 0) {
					uni.navigateTo({
						url: "../select-device/select-device"
					})
				}
			},
			tapchoosePhoto(e) {
				const that = this
				wx.chooseMedia({
					count: 3,
					mediaType: ['image'],
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					camera: 'back',
					success(res) {
						console.log('res6', res);
						that.btndetermine(res.tempFiles)
					}
				})
			},
			async btndetermine(paths) {
				if (paths.length === 0) {
					await showToast({
						title: '请先选择图片'
					})
					return
				}
				let images = []
				let that = this
				for (var i = 0; i < paths.length; i++) {
					uni.uploadFile({
						url: `${baseUrl}api/oct/wemini/file/upload`,
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							openid: uni.getStorageSync("openid") || "oRekA4wN8O7hyfAlgdRNl4ughrm4"
						},
						filePath: paths[i].tempFilePath, // 文件临时路径；
						name: 'file', // 文件名，可以随便写
						formData: {
							type: 'image',
							model: 'task'
						},
						success: function(res) {
							if (res.statusCode === 200) {
								let data = JSON.parse(res.data)
								images.push(data.payload)
							}
							if (images.length === paths.length) {
								that.form.imgPaths = [...that.form.imgPaths, ...images]
								that.tempFilePaths = [...that.tempFilePaths, ...paths.map(item => item
									.tempFilePath)]
							}
						}
					})
				}
			},
		}
	}
</script>

<style lang="less">
	.add-work-main {
		background-color: #f2f6ff;
		padding: 10rpx 30rpx 88rpx;
		font-size: 28rpx;

		image {
			margin: 10rpx;
		}

		.img-list {
			display: flex;

		}

		.job-object {
			.add-job-class {
				margin: 20rpx 0;
				color: #0089FF;
			}

			.job-object-list {
				.item {
					height: 160rpx;
					margin: 30rpx 0;
					padding: 30rpx 20rpx;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.text1 {
						display: flex;
						justify-content: space-between;

						.left {
							color: #0A1B57;

							text:nth-child(1) {
								color: #6490FD;
							}

							text:nth-child(2) {
								margin-left: 20rpx;
							}
						}

						.right {
							z-index: 100;

							.on {
								color: #07C160;
							}

							.off {
								color: #6490FD;
							}
						}
					}

					.text2 {
						color: #A2AFD0;
						display: flex;
						align-items: center;

						>image {
							width: 20rpx;
							height: 28rpx;
						}
					}
				}
			}
		}

		.footer {
			height: 88rpx;
			width: 100vw;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			background-color: @main_bg;
			position: fixed;
			left: 0;
			bottom: 0;
		}
	}
</style>